package com.atguigu.gmall.auth.service.impl;

import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.feign.UmsClient;
import com.atguigu.gmall.auth.service.AuthService;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    UmsClient umsClient;
    @Autowired
    JwtProperties jwtProperties;
    @Override
    public String login(String loginName, String password,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        //远程查询用户数据
        ResponseVo responseVo = umsClient.query(loginName, password);
        if(responseVo.getCode()!=0){
            return null;
        }
        //构建jwt token
        //java.util.LinkedHashMap cannot be cast to com.atguigu.gmall.ums.entity.UserEntity
        //如果ResponseVo的data没有指定泛型   默认对象数据会被Feign客户端转为LinkedHashMap

        Object obj = responseVo.getData();
        ObjectMapper mapper = new ObjectMapper();
        UserEntity userEntity = mapper.convertValue(obj, UserEntity.class);

        Map<String, Object> map = new HashMap<>();
        map.put("userId" , userEntity.getId());
        map.put("username" , userEntity.getUsername());
        map.put("ip" , IpUtils.getIpAddressAtService(request));
        //使用秘钥签名：防止数据被篡改
        //map中可以设置本次登录的客户端ip地址：
        try {
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(),
                    jwtProperties.getExpire() * 24 * 7);
            //将token设置到cookie中交给客户端: response
            //代表登录成功状态的cookie
            CookieUtils.setCookie(request,response,"GMALL-TOKEN",token ,
                    jwtProperties.getExpire() * 24 * 7);
            //交给前端回显登录信息的cookie
            CookieUtils.setCookie(request,response,"unick",userEntity.getNickname() ,
                    jwtProperties.getExpire() * 24 * 7);
////            return token;
            return "1";
        } catch (Exception e) {
            e.printStackTrace();
        }
       return "0";
    }
}
